<template>
  <div class="box">
    <div class="boxTitle">
      <span>创键试卷</span>
      <el-button
        type="primary"
        size="mini"
        style="margin-right: 15px"
        @click="savePaper"
        >保存</el-button
      >
    </div>
    <div class="toplicInfo">
      <div class="toplicT">
        <el-input
          placeholder="请输入试卷名称"
          v-model="form.examinationPaperSummaryName"
        ></el-input>
        <div>
          <span>{{ form.bigProblem }} 大题</span><span>|</span
          ><span>{{ form.questions }} 小题</span><span>|</span
          ><span>总分{{ form.totalPoints }}分 </span>
        </div>
      </div>
      <div class="toplicC">
        <div>
          <span>试卷分类</span>
          <el-popover placement="bottom" width="400" trigger="click">
            <el-input v-model="filterText"></el-input>
            <el-tree
              :data="treeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
              :highlight-current="true"
              :expand-on-click-node="true"
              :default-expand-all="false"
              ref="tree"
              :auto-expand-parent="false"
              :filter-node-method="filterNode"
            >
            </el-tree>

            <el-button slot="reference" type="text" style="margin-left: 15px"
              >{{ temporary.testPaperClassificationName
              }}<i class="el-icon-edit" style="margin-left: 15px"></i
            ></el-button>
          </el-popover>
        </div>
        <span @click="previewEvent">
          <i class="el-icon-view"></i>
          预览
        </span>
      </div>
    </div>
    <div class="inlneBox">
      <div class="bigRight">
        <div class="bigContent">
          <bigQuestion
            v-for="(item, index) in testQuestionsInFo"
            :item="item"
            :key="index"
            @sortEvent="sortEvent"
          ></bigQuestion>
        </div>
        <div class="bigFooter">
          <el-button type="text" @click="addBigQuestion"
            ><i class="el-icon-circle-plus"></i> 新增大题</el-button
          >
        </div>
      </div>
      <div class="topicContent">
        <topicItem
          ref="topicItem"
          @sortEvent="sortEvent"
          @removeBigQuestion="removeBigQuestion"
          v-for="(item, index) in testQuestionsInFo"
          :item="item"
          :key="index"
          :index="index.toString()"
        ></topicItem>
      </div>
    </div>
    <!-- 抽屉预览 -->

    <el-drawer
      :visible.sync="drawer"
      direction="ltr"
      :before-close="handleClose"
    >
      <previewView :id="id"></previewView>
    </el-drawer>
    <!-- 抽屉预览 -->
  </div>
</template>
<script>
import {
  listClassification,
  addSummary,
  getSummary,
  updateSummary,
} from "../../../api/examPaperLibrary";
import bigQuestion from "./bigQuestion.vue";
import topicItem from "./topicItem.vue";
import previewView from "./previewView.vue";
export default {
  components: {
    bigQuestion,
    topicItem,
    previewView,
  },

  data() {
    return {
      form: {
        bigProblem: 0, //大题数量
        questions: 0, //小题数量
        totalPoints: 0, //总分
        testPaperClassificationId: null, //试卷分类id
        examinationPaperSummaryName: "",
        examinationPaperDetailsList: [],
      },
      temporary: {
        testPaperClassificationName: "试卷分类",
      },
      treeData: [],
      treeDataZ: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      filterText: "",
      testQuestionsInFo: [
        {
          name: "第一大题",
          fenzhi: 0,
          sort: 0,
          xiao: [
            // {
            //   xName: "第一小题",
            //   index: 1,
            //   fenzhi: 0,
            //   itemBankId: null,
            //   itemInfo: {},
            //   sort: 0,
            // },
          ],
        },
      ],
      drawer: false,
      id: null, //回显id
    };
  },
  mounted() {
    this.getTreeList();
    if (this.$route.query.examinationPaperSummaryId) {
      this.getTestPaperDetail(this.$route.query.examinationPaperSummaryId);
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    testQuestionsInFo: {
      handler: function (n, o) {
        this.form.bigProblem = n.length;
        let xiaoNum = 0;
        let zongFen = 0;
        n.forEach((ele) => {
          zongFen += ele.fenzhi;
          if (ele.xiao.length != 0) {
            xiaoNum += ele.xiao.length;
          }
        });
        this.form.questions = xiaoNum;
        this.form.totalPoints = zongFen;
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    //初始化
    reserForm(){
      this.form={
        bigProblem: 0, //大题数量
        questions: 0, //小题数量
        totalPoints: 0, //总分
        testPaperClassificationId: null, //试卷分类id
        examinationPaperSummaryName: "",
        examinationPaperDetailsList: [],
      }
      this.temporary={
        testPaperClassificationName: "试卷分类",
      }
      this.testQuestionsInFo= [
        {
          name: "第一大题",
          fenzhi: 0,
          sort: 0,
          xiao: [
          ],
        },
      ]
    }



    ,
    getTreeList() {
      listClassification().then((res) => {
        this.treeData = res.rows;
      });
    },
    //点击树状图
    handleNodeClick(val) {
      console.log(val);
      this.form.testPaperClassificationId = val.id;
      this.temporary.testPaperClassificationName = val.name;
    },
    //树状图节点过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //新增大题
    addBigQuestion() {
      let num = this.testQuestionsInFo.length;

      let obj = {
        name: `第${this.numberToUpperCase(num)}大题`,
        fenzhi: 0,
        sort: num + 1,
        xiao: [
          // {
          //   xName: "第一小题",
          //   index: 1,
          //   fenzhi: 0,
          //   itemBankId: null,
          //   itemInfo: {},
          // },
        ],
      };
      this.testQuestionsInFo.push(obj);
      this.sortEvent();
    },
    //数字边大写数字
    numberToUpperCase(textIndex) {
      let newString = "";
      let newTextIndex = textIndex + 1 + "";

      function sum(value, index) {
        var newValue = "";
        if (textIndex === 9) {
          return !index ? "十" : "";
        }
        let isSeat = ~~textIndex > 9 && ~~textIndex < 19;
        switch (~~value) {
          case 1:
            newValue = !index ? (isSeat ? "" : "一") : "十一";
            break;
          case 2:
            newValue = !index ? (isSeat ? "" : "二") : "十二";
            break;
          case 3:
            newValue = !index ? (isSeat ? "" : "三") : "十三";
            break;
          case 4:
            newValue = !index ? (isSeat ? "" : "四") : "十四";
            break;
          case 5:
            newValue = !index ? (isSeat ? "" : "五") : "十五";
            break;
          case 6:
            newValue = !index ? (isSeat ? "" : "六") : "十六";
            break;
          case 7:
            newValue = !index ? (isSeat ? "" : "七") : "十七";
            break;
          case 8:
            newValue = !index ? (isSeat ? "" : "八") : "十八";
            break;
          case 9:
            newValue = !index ? (isSeat ? "" : "九") : "十九";
            break;
          case 0:
            newValue = "十";
            break;
          default:
            break;
        }
        return newValue;
      }

      for (let i = 0; i < newTextIndex.length; i++) {
        newString += sum(newTextIndex.substring(i, i + 1), i);
      }
      return newString;
    },
    //对数组进行重新排序
    sortEvent() {
      this.testQuestionsInFo.sort(function (a, b) {
        return a.sort - b.sort;
      });
      // setTimeout(() => {
      this.updateSorting(this.testQuestionsInFo);
      // }, 1000);
    },
    //更新排序
    updateSorting(val) {
      val.forEach((ele, index) => {
        this.$set(ele, "sort", index);
        this.$set(ele, "index", index);
      });
    },
    //删除大题
    removeBigQuestion(row) {
      // 获取需要删除元素的索引
      function getRemoveIndex() {
        for (let i = 0; i < this.testQuestionsInFo.length; i++) {
          console.log(this.testQuestionsInFo[i].index, row.index);
          if (this.testQuestionsInFo[i].index === row.index) {
            return i;
          }
        }
        return -1; // 如果没有找到，返回-1
      }

      // 获取要删除的元素的索引
      let indexToRemove = getRemoveIndex.call(this);

      // 如果找到了索引，则使用splice删除元素
      if (indexToRemove !== -1) {
        this.testQuestionsInFo.splice(indexToRemove, 1);
      }

      this.updateSorting(this.testQuestionsInFo);

      // 输出修改后的数组和长度
      console.log(
        this.testQuestionsInFo,
        this.testQuestionsInFo.length,
        indexToRemove,
        "666"
      );
    },
    //预览
    previewEvent() {
      // console.log(this.$refs.topicItem);
      // this.$refs.topicItem.forEach(ele=>{
      //   setTimeout(() => {
      //     ele.submitTopic()
      //   }, 1);
      // })
      // this.rulesEvent();
    },
    //保存试卷
    savePaper() {
      this.rulesEvent().then((res) => {
        if (res) {
          let arr = [];
          this.testQuestionsInFo.forEach((ele) => {
            ele.xiao.forEach((eleinner) => {
              let obj = {
                itemBankId: eleinner.itemBankId,
                bigProblem: ele.name,
                questions: `${eleinner.sort}.${eleinner.itemInfo.questionTypes}`,
                score: eleinner.fenzhi,
                reserve1: ele.sort,
              };
              arr.push(obj);
            });
          });
          this.form.examinationPaperDetailsList = arr;
          console.log(this.form, "传参");
          if (this.form.examinationPaperSummaryId) {
            updateSummary(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                setTimeout(() => {
                  this.$router.back(1);
                }, 1500);
              }
            });
          } else {
            addSummary(this.form).then((res) => {
              if (res.code == 200) {
                // this.$message.success("添加成功");
                this.$message({
                  message: "添加成功",
                  type: "success",
                  customClass: "customClass",
                });
                this.drawer = true;
                this.id = res.msg.split("id为")[1];
                this.reserForm()
                // setTimeout(() => {
                //   this.$router.back(1);
                // }, 1500);
              }
            });
          }
        } else {
          console.log("验证不通过");
        }
      });
    },
    //提交验证方法
    async rulesEvent() {
      if (
        this.form.testPaperClassificationId == null ||
        this.form.testPaperClassificationId == ""
      ) {
        this.$message.error("试卷分类不能为空");
        return false;
      }
      if (this.form.examinationPaperSummaryName == "") {
        this.$message.error("试卷名称不能为空");
        return false;
      }

      for (const ele of this.$refs.topicItem) {
        try {
          const result = await ele.submitTopic(); // 假设submitTopic现在返回Promise
          if (!result) {
            return false;
          }
        } catch (error) {
          return false;
        }
      }

      return true;
    },
    //获取试卷详情(回显)
    getTestPaperDetail(val) {
      getSummary(val).then((res) => {
        if (res.code == 200) {
          let obj = JSON.parse(JSON.stringify(res.data));
          delete obj.examinationPaperDetailsList;
          console.log(obj);
          this.form = obj;
          this.temporary.testPaperClassificationName =
            res.data.testPaperClassification.testPaperClassificationName;

          const transformedData = res.data.examinationPaperDetailsList.reduce(
            (accumulator, currentValue) => {
              // 查找是否已有相应的题号（name1）在累积器中
              const existingItem = accumulator.find(
                (item) => item.name === currentValue.bigProblem
              );
              if (existingItem) {
                // 如果找到，则向xiao数组中添加当前小题对象
                let xiaoObj = {
                  xName: currentValue.questions,
                  itemBankId: currentValue.itemBankId,
                  itemInfo: currentValue.itemBank,
                  fenzhi: currentValue.score,
                  fenzhiIsNull: false,
                  sort: currentValue.questions.split(".")[0],
                };
                existingItem.xiao.push(xiaoObj);
              } else {
                // 如果没有找到，则创建一个新对象，并初始化xiao数组

                let digQu = {
                  name: currentValue.bigProblem,
                  sort: currentValue.reserve1,
                  fenzhi: 0,
                  xiao: [
                    {
                      xName: currentValue.questions,
                      itemBankId: currentValue.itemBankId,
                      itemInfo: currentValue.itemBank,
                      fenzhi: currentValue.score,
                      fenzhiIsNull: false,
                      sort: currentValue.questions.split(".")[0],
                    },
                  ],
                };

                accumulator.push(digQu);
              }

              // 返回累积器以便进行下一次迭代
              return accumulator;
            },
            []
          ); // 初始值为空数组
          console.log(transformedData);
          // this.testQuestionsInFo = transformedData;
          this.$set(this, "testQuestionsInFo", transformedData);
        }
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: #f1f3f8;
  .boxTitle {
    height: 70px;
    background-color: #f7f8fa;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #dcdfe6;
    justify-content: space-between;
    padding: 0 15px;
  }
  .toplicInfo {
    height: 110px;
    background-color: white;
    margin: 20px 20px 0;
  }
  .inlneBox {
    height: 100%;
    // min-height: calc(100% - 70px);
    padding: 20px;
    width: 100%;
    display: flex;
    .bigRight {
      background-color: white;
      width: 300px;
      max-height: 100%;
      position: sticky;
      top: 20px;
      .bigContent {
        max-height: calc(100% - 50px);
        overflow: auto;
      }

      .bigFooter {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 50px;
      }
    }
    .topicContent {
      // height: 100%;
      background-color: white;
      margin-left: 20px;
      padding: 15px 20px;
      overflow: auto;
      flex: 1;
    }
  }
}
.toplicInfo {
  padding: 0 15px;

  .toplicT {
    display: flex;
    justify-content: space-between;
    height: 60px;
    align-items: center;
    .el-input {
      width: 40%;
      min-width: 250px;
    }
    > div {
      > span:nth-of-type(2n) {
        margin: 0 10px;
      }
    }
  }
  .toplicC {
    display: flex;
    justify-content: space-between;
    align-items: center;
    > span {
      background-color: #dcdfe66b;
      font-size: 12px;
      padding: 5px 8px;
      cursor: pointer;
      > i {
        color: #3a63f3;
        margin-right: 5px;
      }
    }
  }
}

.el-popover {
  width: auto !important;
  padding: 15px;
  max-height: 500px;
  overflow: auto;
  > .el-input {
    margin-bottom: 15px;
  }
}

::v-deep .el-drawer {
  width: auto !important;
}
</style>
